package pl.un4giv3n.mightvsmagic.hibernate;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserType;
import pl.un4giv3n.mightvsmagic.utils.ClanStatsUtil;
import pl.un4giv3n.mightvsmagic.utils.StatsUtil;
import pl.un4giv3n.mightvsmagic.utils.UserUtil;

/**
 * @author andrzejewskia
 * this is a filter that injects entity manager into context
 */
public class HibernateFilter extends StrutsPrepareAndExecuteFilter{
	
	/**
	 * emf to create entity managers
	 */
	private EntityManagerFactory factory;
	/**
	 * session entity manager
	 */
	public static String ENTITY_MANAGER_FACTORY = "entityManager";
	
	/* (non-Javadoc)
	 * @see org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		super.init(config);
		factory = Persistence.createEntityManagerFactory("mightvsmagicds");
		EntityManager em = factory.createEntityManager();
		Query query = em.createNamedQuery("find.user.by.login");
		query.setParameter("login", "admin");
		if(query.getResultList().isEmpty()){
			User admin = new User("admin", UserUtil.encyptPassword("tajne69"), "admin@mvsm.pl", UserType.ADMIN);
			em.getTransaction().begin();
			em.persist(admin);
			em.flush();
			em.getTransaction().commit();
		}
		StatsUtil.refreshCache(em);
		ClanStatsUtil.refreshCache(em);
		em.close();
		config.getServletContext().setAttribute(ENTITY_MANAGER_FACTORY, factory);
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		super.doFilter(request, response, chain);
	}
	
	/* (non-Javadoc)
	 * @see org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter#destroy()
	 */
	@Override
	public void destroy() {
		factory.close();
		super.destroy();
	}

}
